package com.wuzuqing.android.eightdiagrams.utils;


//import com.tencent.mmkv.MMKV;
import com.wuzuqing.android.eightdiagrams.model.CalculationTypeModel;
import com.wuzuqing.android.eightdiagrams.model.EightDagramsInfoModel;
import com.wuzuqing.android.eightdiagrams.model.EightDagramsModel;
import com.wuzuqing.android.eightdiagrams.model.MeasureParams;
import com.wuzuqing.android.eightdiagrams.model.MeasureType;
import com.wuzuqing.android.eightdiagrams.model.WenWangShenShuBiaoModel;


import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * 作者：士元
 * 时间：2019/8/9 18:59
 * 邮箱：wuzuqing@linghit.com
 * 说明：
 */
public class EightDagramsManager {
    private List<EightDagramsInfoModel> dagramsInfoModels;
    public static final int EIGHT_BASE = 8;
    public static final int YAO_BASE = 6;

    private EightDagramsModel tiEight;
    private EightDagramsModel yongEight;
    private MeasureType mMeasureType;

    public EightDagramsManager() {
        dagramsInfoModels = new ArrayList<>();
    }

    private static EightDagramsManager sInstance = new EightDagramsManager();

    public static EightDagramsManager getInstance() {
        return sInstance;
    }

    private int[] changeYaoIndex = {4, 2, 0};
    private int topNumber;
    private int bottomNumber;
    private String measureText;

    public void startNumberAndTime(int topNumber, int bottomNumber) {
        int ganZhi = LunarUtil.getInstance().resetNow().getHourZhi();
        int changeYao = getChangeYaoValue(topNumber + bottomNumber + ganZhi);
        startWork(topNumber, bottomNumber, changeYao);
    }

    public void startTime() {
        // 年之天干、月日之数相加之和再除以8得到的余数作为
        // 年之天干、月日之数及时之地支数相加之和再除以8得到的余数作为下卦。
        // 　　10＋7＋1＝18 
        // 年之天干、月日之数及时之地支数相加之和再除以6得到的余数作为动爻。
        LunarUtil now = LunarUtil.getInstance().resetNow();
        measureText = now.getOldData();
        int topNumber = now.geTopNumber();
        int bottomNumber = topNumber + now.getHourZhi();
        startWork(topNumber, bottomNumber, getChangeYaoValue(topNumber + bottomNumber));
    }

    /**
     * @param text 内容
     */
    public void startText(String text) {
        if (DataUtils.isEmpty(text)) {
            return;
        }
        int length = (text.trim().length() + 1) / 2;
        String top = text.substring(0, length);
        String bottom = text.substring(length);
        LunarUtil now = LunarUtil.getInstance().resetNow();
        int hourZhi = now.getHourZhi();
        int topNumber = CnToStrokeCount.getStringStrokeCount(top);
        int bottomNumber = CnToStrokeCount.getStringStrokeCount(bottom);
        startWork(topNumber, bottomNumber, getChangeYaoValue(topNumber + bottomNumber + hourZhi));
    }


    /**
     * 最简单的
     *
     * @param topNumber
     * @param bottomNumber
     */
    public void startNumber(int topNumber, int bottomNumber) {
        startWork(topNumber, bottomNumber, getChangeYaoValue(topNumber + bottomNumber));
    }

    private static final String MEASURE_HISTORY = "measure_list";


    public static List<MeasureParams> getHistory() {
//        String measure_list = MMKV.defaultMMKV().getString(MEASURE_HISTORY, "");
        List<MeasureParams> list = new ArrayList<>();
//        if (!measure_list.isEmpty()) {
//            list.addAll(JsonParserUtil.parseJsonList(measure_list, MeasureParams.class));
//        }
        return list;
    }

    public void startMeasure(MeasureParams params) {
        setMeasureType(params.getType());
        if (!params.isHistory()) {
            List<MeasureParams> list = getHistory();
            params.setHistory(true);
            list.add(params);
//            MMKV.defaultMMKV().putString(MEASURE_HISTORY, JsonParserUtil.toJson(list));
        }
        switch (params.getType()) {
            case TIME:
                startTime();
                break;
            case SELECT:
                this.topNumber = params.getTopNumber();
                this.bottomNumber = params.getBottomNumber();
                startWork(params.getTopNumber(),params.getBottomNumber(),params.getYaoIndex());
                break;
            case TEXT:
                measureText = params.getText();
                startText(params.getText());
                break;
            case NUMBER:
                this.topNumber = params.getTopNumber();
                this.bottomNumber = params.getBottomNumber();
                startNumber(topNumber, bottomNumber);
                break;
            case NUMBER_AND_TIME:
                this.topNumber = params.getTopNumber();
                this.bottomNumber = params.getBottomNumber();
                startNumberAndTime(params.getTopNumber(), params.getBottomNumber());
                break;
        }
    }

    public void startWork(int topNumber, int bottomNumber, int changeYao) {
        dagramsInfoModels.clear();
        int topEightIndex = changeDefaultValue(topNumber % EIGHT_BASE, EIGHT_BASE);
        int bottomEightIndex = changeDefaultValue(bottomNumber % EIGHT_BASE, EIGHT_BASE);

        EightDagramsModel topEight = DataUtils.getEightDagrams(topEightIndex);
        EightDagramsModel bottomEight = DataUtils.getEightDagrams(bottomEightIndex);
        // 本卦
        EightDagramsInfoModel model = DataUtils.getEightDagramsInfo("本卦", topEightIndex, bottomEightIndex);
        model.setDynamicYao(changeYao);
        dagramsInfoModels.add(model);

        String allYao = String.format(Locale.getDefault(), "%s-%s", topEight.getYaoFlag(), bottomEight.getYaoFlag());
        if (changeYao > 3) {
            EightDagramsModel change = getChangeEight(topEight, changeYaoIndex[changeYao - 4]);
            tiEight = bottomEight.cloneSelf();
            yongEight = topEight.cloneSelf();
            dagramsInfoModels.add(DataUtils.getEightDagramsInfo("变卦", change, bottomEight));
        } else {
            EightDagramsModel change = getChangeEight(bottomEight, changeYaoIndex[changeYao - 1]);
            tiEight = topEight.cloneSelf();
            yongEight = bottomEight.cloneSelf();
            // 下挂
            dagramsInfoModels.add(DataUtils.getEightDagramsInfo("变卦", topEight, change));
        }

        dagramsInfoModels.add(DataUtils.getEightDagramsInfo("互卦",
                DataUtils.getEightDagrams(allYao.substring(2, 7)),
                DataUtils.getEightDagrams(allYao.substring(4, 9))));


        dagramsInfoModels.add(DataUtils.getEightDagramsInfo("错卦", getChangeAllYao(topEight),
                getChangeAllYao(bottomEight)));

        StringBuffer str = new StringBuffer(allYao).reverse();
        dagramsInfoModels.add(DataUtils.getEightDagramsInfo("综卦",
                DataUtils.getEightDagrams(str.substring(0, 5)),
                DataUtils.getEightDagrams(str.substring(6, 11))));
    }


    public String getResult() {
        StringBuilder sb = new StringBuilder();
        sb.append("测试方式");
        switch (mMeasureType) {
            case TIME:
                sb.append("时间起卦").append(":").append(measureText);
                break;
            case NUMBER:
                sb.append("数目起卦").append(":").append("上挂=").append(topNumber).append(",下挂=").append(bottomNumber);
                break;
            case NUMBER_AND_TIME:
                sb.append("数目加时间起卦").append(":").append("上挂=").append(topNumber).append(",下挂:").append(bottomNumber)
                        .append("时间=").append(LunarUtil.getInstance().resetNow().getHourZhi());
                break;
            case TEXT:
                sb.append("汉字起卦").append(":").append(measureText);
                break;
            case SELECT:
                sb.append("指定起卦").append(":").append("上挂=").append(topNumber).append(",下挂=").append(bottomNumber);
                break;
        }
        sb.append("\n");
        if (tiEight != null && yongEight != null) {
            String tiWx = tiEight.getWuXing();
            String yongWx = yongEight.getWuXing();
            sb.append("体卦:").append(tiEight.getEightDiagramsName()).append(tiWx).append("\n");
            sb.append("用挂:").append(yongEight.getEightDiagramsName()).append(yongWx).append("\n");
            String wuXing = DataUtils.getWuXing(tiWx, yongWx);
            sb.append(wuXing).append("\n");
        }
        for (EightDagramsInfoModel model : dagramsInfoModels) {
            sb.append(model.toString())
//                    .append("\n").append(DataUtils.getDetail(model.getEightDiagramsId()).toString()).append("\n")
                    ;
        }
        return sb.toString();
    }

    public EightDagramsModel getTiEight() {
        return tiEight;
    }

    public EightDagramsModel getYongEight() {
        return yongEight;
    }

    public List<EightDagramsInfoModel> getDagramsInfoModels() {
        return dagramsInfoModels;
    }

    private EightDagramsModel getChangeEight(EightDagramsModel topEight, int changeYaoIndex) {
        String yaoFlag = topEight.getYaoFlag();
        int realIndex = changeYaoIndex;
        char[] chars = yaoFlag.toCharArray();
        chars[realIndex] = changeChar(realIndex, chars);
        String newYao = new String(chars);
        return DataUtils.getEightDagrams(newYao);
    }

    private char changeChar(int realIndex, char[] chars) {
        return chars[realIndex] == '1' ? '0' : '1';
    }

    private EightDagramsModel getChangeAllYao(EightDagramsModel topEight) {
        String yaoFlag = topEight.getYaoFlag();
        char[] chars = yaoFlag.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] != '-') {
                chars[i] = changeChar(i, chars);
            }
        }
        String newYao = new String(chars);
        return DataUtils.getEightDagrams(newYao);
    }

    private int changeDefaultValue(int currentValue, int defaultValue) {
        return currentValue == 0 ? defaultValue : currentValue;
    }

    private int getChangeYaoValue(int value) {
        return changeDefaultValue(value % YAO_BASE, YAO_BASE);
    }

    private int[] shunXu = {1, 6, 7, 4, 5, 3, 8, 2, 1, 6, 7, 4, 5, 3, 8, 2};

    public WenWangShenShuBiaoModel getContent(int number, String type) {

        int yeShu = number % 8;
        if (yeShu == 0) {
            yeShu = 8;
        }
        CalculationTypeModel model = DataUtils.getCalculationType(type);
        int shiWei = indexOf(model.getShiWei()) - 1 + yeShu;
        int geWei = indexOf(model.getGeWei()) - 1 + yeShu;
        WenWangShenShuBiaoModel shenShu = DataUtils.getWenWangShenShu(yeShu, shunXu[shiWei], shunXu[geWei]);
        LogUtils.d("yeShu:" + yeShu + " model:" + model + " shenShu:" + shenShu + "" + " shiWei:" + shiWei + " geWei" +
                ":" + geWei);
//        index+yeShu  1, 6, 7, 4, 5, 3, 8, 2,1, 6, 7, 4, 5, 3, 8, 2
        //             0  1  2  3  4  5  6  7 8  9  10 11 12 13 14 15
//        3   5+5 -1
//        2  7+5-1

        return shenShu;
    }

    private int indexOf(int value) {
        for (int i = 0; i < shunXu.length; i++) {
            if (shunXu[i] == value) {
                return i;
            }
        }
        return 0;
    }


    public void setMeasureType(MeasureType type) {
        this.mMeasureType = type;
    }
}
